package com.lagou.zkClient;

import com.lagou.service.DataSourceBuilder;
import com.lagou.service.ZkConfigService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @author
 */
@Component
public class ZkConfigListener implements PathChildrenCacheListener,CommandLineRunner {

    private static CuratorFramework zkClient = ZkClientFactory.getZkClient();

    @Override
    public void run(String... args) throws Exception {
        DataSourceBuilder.build();

        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, ZkConfigService.DATABASE_CONFIG, true);
        pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        pathChildrenCache.getListenable().addListener(new ZkConfigListener());
    }

    @Override
    public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {

        switch (pathChildrenCacheEvent.getType()){
            case CHILD_UPDATED:
                DataSourceBuilder.build();
                break;
            case CHILD_ADDED:
                DataSourceBuilder.build();
                break;
            case CHILD_REMOVED:
                DataSourceBuilder.destroyDataSource();
        }
    }
}
